package studyguide.ch18;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Gauge;
import javax.microedition.lcdui.TextField;
import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;

public class TonePlayingForm extends Form {

	private final SoundPlayerMidlet parent;
	
	private final Command playCommand;
	private final Command backCommand;
	
	private final Gauge noteField; 
	private final TextField durationField; 
	private final Gauge volumeField;
	
	private class PlayerCommandListener implements CommandListener {
		public void commandAction(Command command, Displayable d) {
			try {
				if (command == playCommand) {
					int note = 10 * noteField.getValue();
					int duration = Integer.parseInt(durationField.getString());
					int volume = 10 * volumeField.getValue();
					Manager.playTone(note, duration, volume);
				} else if (command == backCommand) {
					parent.showMainScreen();
				} else {
					throw new RuntimeException("UNKNOWN COMMAND:" + command);
				}
			} catch (MediaException e) {
				throw new RuntimeException("Error:" + e);
			}
		}
	}
	
	public TonePlayingForm(SoundPlayerMidlet parent) {
		super("Tone");
		this.parent = parent;
		noteField = new Gauge("Note", true, 12, 10);
		durationField = new TextField("Duration", "700", 5, TextField.NUMERIC);
		volumeField = new Gauge("Volume", true, 10, 9);
		
		append(noteField);
		append(durationField);
		append(volumeField);
		
		playCommand = new Command("Play", Command.SCREEN, 1);
		backCommand = new Command("Back", Command.BACK, 1);
		
		addCommand(playCommand);
		addCommand(backCommand);
		setCommandListener(new PlayerCommandListener());
	}
	
}
